// merchandise detail page
import api from '../../../services/api'

Page({
  data: {
    id: '',
    product: {},
    loading: false,
    isLoggedIn: false,
    hasLiked: false,
    currentImageIndex: 0,
    imageList: []
  },
  
  onLoad(options) {
    if (options && options.id) {
      this.setData({
        id: options.id,
        loading: true
      });
      this.fetchProductDetail(options.id);
      this.checkLoginStatus();
    } else {
      wx.showToast({
        title: '商品ID不存在',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    this.setData({
      isLoggedIn: !!token
    });
  },
  
  // 获取商品详情
  fetchProductDetail(id) {
    this.setData({ loading: true });
    
    api.merchandise.details(id)
      .then(res => {
        console.log('商品详情数据:', res);
        if (res.status === 200 && res.data) {
          const productData = res.data;
          
          // 处理图片列表
          let imageList = [];
          if (productData.pictureList) {
            imageList = productData.pictureList.split('|')
              .filter(url => url.trim()) // 过滤空URL
              .map(url => {
                return url.startsWith('http') ? url : `https://${url}`;
              });
          }
          
          // 处理封面图
          if (productData.cover) {
            productData.image = productData.cover.startsWith('http') ? 
              productData.cover : `https://${productData.cover}`;
          }
          
          // 如果没有图片列表但有封面图，将封面图添加到图片列表
          if (imageList.length === 0 && productData.image) {
            imageList.push(productData.image);
          }
          
          // 如果没有任何图片，添加默认图片
          if (imageList.length === 0) {
            imageList.push('/images/product-placeholder.png');
          }
          
          this.setData({
            product: {
              ...productData,
              id: productData.autoId,
              title: productData.productName,
              price: productData.price,
              description: productData.productIntroduce,
              likes: productData.likeNum || 0
            },
            imageList: imageList,
            loading: false
          });

          // 添加动态标题
          wx.setNavigationBarTitle({
            title: productData.productName || '商品详情'
          });
        } else {
          this.handleFetchError(res.message || '获取商品详情失败');
        }
      })
      .catch(err => {
        console.error('获取商品详情失败:', err);
        this.handleFetchError('网络错误，请稍后重试');
      });
  },
  
  // 处理数据获取失败
  handleFetchError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
    this.setData({ 
      loading: false,
      product: {},
      imageList: []
    });
  },
  
  // 商品点赞
  handleLike() {
    // 检查是否登录
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '需要登录后才能点赞',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    if (this.data.hasLiked) {
      wx.showToast({
        title: '您已经点过赞了',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    api.merchandise.doLike(this.data.id)
      .then(res => {
        console.log('点赞结果:', res);
        this.setData({ loading: false });
        
        if (res.status === 200) {
          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          });
          
          // 更新点赞状态和数量
          this.setData({
            hasLiked: true,
            'product.likes': (this.data.product.likes || 0) + 1
          });
        } else {
          wx.showToast({
            title: res.message || '点赞失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('点赞失败:', err);
        wx.showToast({
          title: '点赞失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },
  
  // 切换图片
  changeImage(e) {
    const index = e.currentTarget.dataset.index;
    if (index >= 0 && index < this.data.imageList.length) {
      this.setData({
        currentImageIndex: index
      });
    }
  },
  
  // 预览图片
  previewImage() {
    if (this.data.imageList.length > 0) {
      wx.previewImage({
        current: this.data.imageList[this.data.currentImageIndex],
        urls: this.data.imageList
      });
    }
  },
  
  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  },
  
  // 分享功能
  onShareAppMessage() {
    const product = this.data.product;
    return {
      title: product.title || 'KSG周边商品',
      path: `/pages/merchandise/detail/index?id=${this.data.id}`,
      imageUrl: this.data.imageList.length > 0 ? this.data.imageList[0] : ''
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const product = this.data.product;
    return {
      title: product.title || 'KSG周边商品',
      query: `id=${this.data.id}`,
      imageUrl: this.data.imageList.length > 0 ? this.data.imageList[0] : ''
    };
  },
  
  // 页面显示
  onShow() {
    // 检查登录状态，以防用户从登录页返回
    this.checkLoginStatus();
  }
}) 